<?php
namespace app\index\controller;

use think\Cache;
use think\Db;
use think\Controller;
use think\Session;
use think\Config;
use think\Log;

use alidayu_sms\Ali_sms;
use mredis\Mredis;
use vcode\Vcode;


class Index extends Controller
{

    function __construct() {
        parent::__construct();
        $this->get_front_menu();//读取前台菜单和友情链接
        $this->get_webinfo();//获取网站优化信息
    }

    //首页
    public function index(){
        $web_info = Db::name('system')->where('id',1)->find();//查询网站标题
        $this->assign('web_info', $web_info);
        $banner_where['status'] = 1;
        $banner_lists = Db::name('advert')->where($banner_where)->order('id desc')->select();//查询网站banner
        $this->assign('banner_lists', $banner_lists);
        $product_where['column'] = 9;
        $product_where['status'] = 1;
        $product_lists = Db::name('product')->where($product_where)->field('id,title,image,seo_name_en,column_name')->order('id desc')->limit(20)->select();
        $this->assign('product_lists', $product_lists);
//        $news_where['type'] = 2;
//        $news_where['status'] = 1;
//        $news_lists = Db::name('article')->where($news_where)->field('id,title,describe,add_time,column_name,seo_name_en')->order('id desc')->limit(8)->select();//查询点赞的所有文章
//        $this->assign('news_lists', $news_lists);
        $case_where['s_column'] = 5;
        $case_where['status'] = 1;
        $case_lists = Db::name('article')->where($case_where)->field('id,title,image,seo_name_en,column_name')->order('id desc')->limit(4)->select();
        $this->assign('case_lists', $case_lists);
        return $this->fetch('index/index');
    }
    //获取前台栏目和友情链接
    public function get_front_menu(){
        $nav_where['status'] = 1;
        $nav_lists = Db::name('navigation')->where($nav_where)->order('sort desc')->select();
        $this->assign('nav_lists', $nav_lists);
        $friendly_where['status'] = 1;
        $friendly_link = Db::name('friendly_link')->where($friendly_where)->order('id desc')->select();
        $this->assign('friendly_link', $friendly_link);
    }
    //获取网站信息
    public function get_webinfo(){
        $web_seo = Db::name('system')->where('id',1)->find();
        $spider = robots();
        if($spider){
            $data['spider'] = $spider['spider'];
            $data['time'] = strtotime($spider['date']);
            $data['ip'] = $spider['ip'];
            $data['url'] = $spider['url'];
            $status = Db::name('spider')->insert($data);
        }
        $this->assign('web_seo', $web_seo);
    }

    //tag标签
    public function tag($name=''){
        if(empty($name)){//tags列表
            $where['status'] = 1;
            $tag_lists = Db::name('tags')->where($where)->order('id desc')->select();
            die();
        }
        $where['status'] = 1;
        $where['title'] = $name;
        $tag_detail = Db::name('tags')->field('id,title,keywords,describe')->where($where)->find();
        $web_info['web_title'] = $tag_detail['title'];
        $web_info['web_keywords'] = $tag_detail['keywords'];
        $web_info['web_descript'] = $tag_detail['describe'];
        $this->assign('web_info', $web_info);

        $this->assign('data', $tag_detail);
        $this->assign('data', $tag_detail);
        $a_where['a.tid'] = $tag_detail['id'];
        $a_where['a.status'] = 1;
        $join = [
            ['lh_article b','a.aid=b.id'],
        ];
        $tag_lists = Db::name('tag_relation')->alias('a')->where($a_where)->join($join)->field('a.id,b.title,b.describe,b.add_time,b.column_name,b.seo_name_en')->order('id desc')->paginate(10);
        $this->assign('lists', $tag_lists);

        $inside_where['inside'] = 1;
        $inside_lists = Db::name('navigation')->where($inside_where)->order('sort desc')->select();//获取内页显示的栏目
        $this->assign('inside_lists',$inside_lists);

        $news_where['type'] = 1;
        $news_where['status'] = 1;
        $news_lists = Db::name('article')->where($news_where)->field('id,title,describe,add_time,column_name,seo_name_en')->order('id desc')->limit(6)->select();//查询点赞的所有文章
        $this->assign('news_lists', $news_lists);

        return $this->fetch('index/list_tag');
    }
    //留言
    public function message(){
        $inside_where['inside'] = 1;
        $inside_lists = Db::name('navigation')->where($inside_where)->order('sort desc')->select();//获取内页显示的栏目
        $this->assign('inside_lists',$inside_lists);

        $news_where['type'] = 1;
        $news_where['status'] = 1;
        $news_lists = Db::name('article')->where($news_where)->field('id,title,describe,add_time,column_name,seo_name_en')->order('id desc')->limit(6)->select();//查询点赞的所有文章
        $this->assign('news_lists', $news_lists);

        $dao = new \app\model\admin\System();
        $web_info = $dao->web_info();//查询网站标题
        $this->assign('web_info', $web_info);
        $data['message_token']=$this->request->token('message_token');
        $this->assign('data', $data);
        return $this->fetch('index/message');
    }

    //留言插入
    public function message_insert(){
        $name = deletehtml($this->request->post('name'));
        $phone = deletehtml($this->request->post('phone'));
        $remark = deletehtml($this->request->post('remark'));
        $captcha = deletehtml($this->request->post('captcha'));

        $code_type = deletehtml($this->request->post('code_type'));
        if(empty($name))return json(['status'=>1001,'data'=>'','msg'=>'请输入姓名!']);
        if(empty($phone))return json(['status'=>1002,'data'=>'','msg'=>'请输入手机号!']);
        if(empty($remark))return json(['status'=>1003,'data'=>'','msg'=>'请输入咨询的内容!']);

        $code_typeq = Session::get($code_type);
        $code_img = $code_typeq['pc_code'];

        if($code_img!=$captcha){
            return json(['status'=>1004,'data'=>(object)[],'msg'=>'验证码错误!']);
        }
        $data['name'] = $name;
        $data['phone'] = $phone;
        $data['message'] = $remark;
        $data['time'] = time();
        $this->weixin_remind($data);
        $data = Db::name('message')->insert($data);
        Session::set('pc_code','');
        if($data)return json(['status'=>0,'data'=>'','msg'=>'操作成功!']);
        else return json(['status'=>1004,'data'=>'','msg'=>'留言失败!']);
    }

    //联系我们
    public function contact(){
        $inside_where['inside'] = 1;
        $inside_lists = Db::name('navigation')->where($inside_where)->order('sort desc')->select();//获取内页显示的栏目
        $this->assign('inside_lists',$inside_lists);

        $news_where['type'] = 1;
        $news_where['status'] = 1;
        $news_lists = Db::name('article')->where($news_where)->field('id,title,describe,add_time,column_name,seo_name_en')->order('id desc')->limit(6)->select();//查询点赞的所有文章
        $this->assign('news_lists', $news_lists);
        $data = Db::name('pages')->where('id',3)->find();
        $web_info['web_title'] = $data['title'];
        $web_info['web_keywords'] = $data['keywords'];
        $web_info['web_descript'] = $data['describe'];
        $this->assign('web_info',$web_info);

        $this->assign('data', $data);
        return $this->fetch('index/page');
    }
    //关于我们
    public function about(){
        $inside_where['inside'] = 1;
        $inside_lists = Db::name('navigation')->where($inside_where)->order('sort desc')->select();//获取内页显示的栏目
        $this->assign('inside_lists',$inside_lists);

        $news_where['type'] = 1;
        $news_where['status'] = 1;
        $news_lists = Db::name('article')->where($news_where)->field('id,title,describe,add_time,column_name,seo_name_en')->order('id desc')->limit(6)->select();//查询点赞的所有文章
        $this->assign('news_lists', $news_lists);
        $data = Db::name('pages')->where('id',2)->find();
        $web_info['web_title'] = $data['title'];
        $web_info['web_keywords'] = $data['keywords'];
        $web_info['web_descript'] = $data['describe'];
        $this->assign('web_info',$web_info);

        $this->assign('data', $data);
        return $this->fetch('index/about');
    }

    //短信发送
    public function send(){
        $sms = new \app\model\Ali_sms();
        $sms_status = $sms->send('17612176345','短信测试','SMS_47055114','{code:\'1111\'}');
        if($sms_status){
            var_dump(1);
        }else{
            var_dump(2);
        }
        die();
    }

    //邮件发送
    public function mail(){
        $sms = new \app\model\Mail_send();
        $addaddress = 'fisher@chinaluohong.com';
        $email_title = '邮件测试标题';
        $email_content = '邮件测试内容';
        $sms_status = $sms->mail_send($addaddress,$email_title,$email_content,'');
        if($sms_status){
            var_dump(1);
        }else{
            var_dump(2);
        }
    }

    //微信提醒
    public function weixin_remind($web_info){
        $web_seo = Db::name('system')->where('id',1)->find();//查询网站标题
        Config::load(APP_PATH.'other.php');
        $appid = "wx1cc8937e93e20414";
        $appsecret = "a47f95c7fb5c0744971ed13ab741e727";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $file = http_curl($url);
        $josn = json_decode($file,true);
        $token = $josn['access_token'];
        $openid[] = 'oCyHOjsdursiwar3RD0gm5idIgMU';//克长虎
        $openid[] = 'oCyHOjuTPaF30cLsalE8RMFG2CXg';//王帅
        foreach($openid as $val){
            $data =' {
            "touser":"'.$val.'",
            "template_id":"nMHsFQGgWKhUvzLFyWr-iaQa96ntra_MrXDC6_4e5I0",
            "url":"'.Config::get('web_url').'",
            "data":{
                "web_title": {
                "value":"'.$web_seo['web_title'].'",
                "color":"#f50c0c"
                },
                "web_url": {
                "value":"'.Config::get('web_url').'",
                "color":"#f50c0c"
                },
                "web_name": {
                "value":"'.$web_info['name'].'",
                "color":"#f50c0c"
                },
                "web_tel": {
                "value":"'.$web_info['phone'].'",
                "color":"#f50c0c"
                },
                "web_con": {
                "value":"'.$web_info['message'].'",
                "color":"#f50c0c"
                },
                "web_time": {
                "value":"'.date("Y-m-d H:i:s") .'",
                "color":"#f50c0c"
                }
            }
          }';
            $data = urldecode($data);
            $send = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token."";
            $res = http_curl($send,'POST',$data);
            $status[] = json_decode($res,true);
        }

        Log::record($status);
    }

    //支付宝支付
    public function alipay(){
        Log::record(11);
        $data['order_num'] =get_order_num();
        $data['uid'] =1;
        $data['pid'] =1;
        $data['money'] ='0.01';
        $data['order_status'] ='1';
        $data['add_time'] =time();
        $data['status'] =1;
        $dao = new \app\model\front\Order();
        $order_status = $dao->add_order($data);
        if($order_status){//订单插入成功则进行支付
            $pay = new \app\model\Pay();
            $alipay = $pay->alipay(1,$data['order_num'],'订单名称', $data['money'],'商品描述');
        }
    }

    //支付宝异步通知地址
    public function alipay_notify(){
        $pay = new \app\model\Pay();
        $alipay_result = $pay->alipay_notify();

    }

    //支付宝同步跳转
    public function alipay_return(){
        var_dump('ok');
    }

    function tongji(){
        $tongji_time = Session::get('tongji_time');
        if($tongji_time+3>time()){//防止恶意刷新该接口，默认3s才算一个正常的访问
            return json(['status'=>9999,'data'=>'','msg'=>'Time is too fast!']);
        }
        //在搜索引擎搜索个关键词，进入网站
        $referer = $this->search_word_from($this->request->post('referer'));
        Session::set('tongji_time',time());
        $data['ip'] = getIP();
        $data['time'] = time();
        $data['date'] = strtotime(date("Y-m-d",time()));
        $data['keyword'] =  $referer['keyword'];//来源关键词
        $data['source_web'] =  $referer['from'];//来源网站
        $data['type'] =  $referer['type'];//来源终端1pc2手机端
        $data['url'] = $this->request->post('url');//获取首次访问的地址

        $where['ip'] = $data['ip'];
        $where['date'] = $data['date'];
        $where['keyword'] = $data['keyword'];
        $where['source_web'] = $data['source_web'];
        $where['type'] = $data['type'];
        $status = Db::name('tongji')->where($where)->find();
        if(!empty($status)){
            $status = Db::name('tongji')->where('id', $status['id'])->update(['num' => ['exp','num+1']]);
        }else{
            $status = Db::name('tongji')->insert($data);
        }
        if($status)return json(['status'=>0,'data'=>'','msg'=>'ok!']);
        else return json(['status'=>9999,'data'=>'','msg'=>'fail!']);
    }
    function search_word_from($referer) {
        if(!isMobile()){//pc统计
            $type=1;//pc端
            if(strstr( $referer, 'baidu.com')){ //百度
                preg_match( "|baidu.+wo?r?d=([^\\&]*)|is", $referer, $tmp );
                $keyword = urldecode( $tmp[1] );
                $from = 'baidu';
            }elseif(strstr( $referer, 'google.com') or strstr( $referer, 'google.cn')){ //谷歌
                preg_match( "|google.+q=([^\\&]*)|is", $referer, $tmp );
                $keyword = urldecode( $tmp[1] );
                $from = 'google';
            }elseif(strstr( $referer, 'so.com')){ //360搜索
                preg_match( "|so.+q=([^\\&]*)|is", $referer, $tmp );
                $keyword = urldecode( $tmp[1] );
                $from = '360';
            }elseif(strstr( $referer, 'sogou.com')){ //搜狗
                preg_match( "|sogou.com.+query=([^\\&]*)|is", $referer, $tmp );
                $keyword = urldecode( $tmp[1] );
                $from = 'sogou';
            }else {
                $keyword ='';
                $from = '';
            }
        }else{//手机端统计
            $keyword ='';
            $from = '';
            $type=2;//手机端
        }
        return array('keyword'=>$keyword,'from'=>$from,'type'=>$type);
    }



    //验证码
    function pc_code() {
        $code = $this->request->get('code');
        if(empty($code))$code = 'code';
        getCode(4,50,20,$code);
    }
    function city(){
        $province_id = (int)$this->request->get('province_id');
        if(!$province_id){
            $where['resource']=1;
            $province_lists = Db::name('province')->field('id,name')->where($where)->order('id asc')->select();
            return json(['status'=>0,'data'=>$province_lists,'msg'=>'ok!']);
        }
        $where['province_id'] = $province_id;
        $city_lists = Db::name('city')->field('id,city')->where($where)->order('id asc')->select();
        return json(['status'=>0,'data'=>$city_lists,'msg'=>'ok!']);
    }

    function sitemap_xml(){
        Config::load(APP_PATH.'other.php');
        $web_url = Config::get('url');//网站地址
        $web_info1['url'] = $web_url;
        $web_info1['time'] = date('Y-m-d H:i:s',time());
        $web_info1['pr'] = '1.0';
        $web_info[] = $web_info1;

        $c_dao = new \app\model\admin\Column();
        $a_dao = new \app\model\front\Article();
        $c_where['status']=1;
        $c_lists = $c_dao->get_column_lists($c_where,$sort='id desc',$paginate=10);
        if($c_lists){
            foreach($c_lists as $val){
                $c_url = $web_url.$val['seo_name_en'];
                $web_info_c1['url'] = $c_url;
                $web_info_c1['time'] = date('Y-m-d H:i:s',$val['add_time']);
                $web_info_c1['pr'] = '0.8';
                $web_info_c[] = $web_info_c1;
            }
        }
        $tag_where['status'] = 1;
        $tag_lists = Db::name('tags')->where($tag_where)->order('id desc')->select();
        $this->assign('tag_lists', $tag_lists);
        if($tag_lists){
            foreach($tag_lists as $val){
                $c_url = $web_url.'tag/'.$val['title'];
                $web_info_c1['url'] = $c_url;
                $web_info_c1['time'] = date('Y-m-d H:i:s',$val['add_time']);
                $web_info_c1['pr'] = '0.8';
                $web_info_c[] = $web_info_c1;
            }
        }

        $where['status']='1';
        $a_lists = $a_dao->get_article_all($where,$sort='id desc');//查询所有文章
        if($a_lists){
            foreach($a_lists as $val){
                $a_url = $web_url.$val['column_name'].'/'.$val['seo_name_en'].'.html';
                $web_info_a1['url'] = $a_url;
                $web_info_a1['time'] = date('Y-m-d H:i:s',$val['add_time']);
                $web_info_a1['pr'] = '0.5';
                $web_info_a[] = $web_info_a1;
            }

        }
        header("Content-Type: text/xml; charset=utf-8");
        $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        $xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
        $xml .= $this->arrayToXml($web_info_a);
        $xml .= $this->arrayToXml($web_info_c);
        $xml .= $this->arrayToXml($web_info);
        $xml .= '</urlset>';
        echo $xml;
        exit;
    }

    //网站地图-html
    function sitemap_html(){
        $url = [];
        $dao = new \app\model\admin\System();
        $a_dao = new \app\model\front\Article();
        $web_info = $dao->web_info();//查询网站标题
        $this->assign('web_info', $web_info);

        $url[] = $web_url = Config::get('url'); //网站地址

        $c_where['status']=1;
        $c_lists = Db::name('column')->where($c_where)->order('id desc')->select();
        $this->assign('c_lists', $c_lists);
        if($c_lists){
            foreach($c_lists as $val){
                $url[] = $web_url.$val['seo_name_en'];
            }
        }

        $where['status']='1';
        $a_lists = Db::name('article')->where($where)->order('id desc')->select();//查询所有文章
        $this->assign('a_lists', $a_lists);
        if($a_lists){
            foreach($a_lists as $val){
                $url[] = $web_url.$val['column_name'].$val['seo_name_en'].'.html';
            }
        }

        $tag_where['status'] = 1;
        $tag_lists = Db::name('tags')->where($tag_where)->order('id desc')->select();
        $this->assign('tag_lists', $tag_lists);
        if($tag_lists){
            foreach($tag_lists as $val){
                $url[] = $web_url.'/tag/'.$val['title'];
            }
        }

        //存在百度推送token
        if(!empty($web_info['baidu_token'])){
            baidu_tuisong($web_info['baidu_token'],$url);
        }
        return $this->fetch('sitemap/html');
    }

    //数组转XML
    function arrayToXml($arr)
    {
        $xml = "";
        foreach ($arr as $val)
        {
            $xml .= "<url>\n";
            $xml .= '<loc>'.$val['url'].'</loc>';
            $xml .= '<lastmod>'.$val['time'].'+08:00</lastmod>';
            $xml .= '<changefreq>monthly</changefreq>';
            $xml .= '<priority>'.$val['pr'].'</priority>';
            $xml .= "</url>\n";
        }
        return $xml;
    }

}


